<template>
  <div class="file-upload">
    <el-upload
      ref="upload"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :data="uploadData"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :limit="limit"
      :on-exceed="handleExceed"
      :accept="accept"
      :multiple="multiple"
      :show-file-list="showFileList"
      :list-type="listType"
      :disabled="disabled"
      class="upload-component"
    >
      <template v-if="listType === 'picture-card'">
        <i class="el-icon-plus"></i>
      </template>
      <template v-else>
        <el-button size="small" type="primary" :disabled="disabled">
          <i class="el-icon-upload"></i>
          {{ buttonText }}
        </el-button>
      </template>
      <div slot="tip" class="el-upload__tip" v-if="tip">
        {{ tip }}
      </div>
    </el-upload>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="previewVisible" title="图片预览" width="800px">
      <img :src="previewUrl" style="width: 100%" alt="预览图片" />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'FileUpload',
  props: {
    // 上传文件的值
    value: {
      type: [String, Array],
      default: () => []
    },
    // 上传文件类型
    fileType: {
      type: String,
      default: 'image' // image, document, all
    },
    // 文件大小限制(MB)
    fileSize: {
      type: Number,
      default: 10
    },
    // 文件数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否显示文件列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 列表类型
    listType: {
      type: String,
      default: 'text' // text, picture, picture-card
    },
    // 按钮文字
    buttonText: {
      type: String,
      default: '选择文件'
    },
    // 提示文字
    tip: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      previewVisible: false,
      previewUrl: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/file/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadData: {
        type: this.fileType
      }
    }
  },
  computed: {
    accept() {
      const acceptMap = {
        image: 'image/*',
        document: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt',
        all: '*'
      }
      return acceptMap[this.fileType] || '*'
    }
  },
  watch: {
    value: {
      handler(val) {
        this.initFileList(val)
      },
      immediate: true
    }
  },
  methods: {
    // 初始化文件列表
    initFileList(value) {
      if (!value) {
        this.fileList = []
        return
      }

      let files = []
      if (typeof value === 'string') {
        try {
          files = JSON.parse(value)
        } catch {
          files = value ? [{ url: value, name: this.getFileName(value) }] : []
        }
      } else if (Array.isArray(value)) {
        files = value
      }

      this.fileList = files.map((file, index) => ({
        uid: file.uid || Date.now() + index,
        name: file.name || this.getFileName(file.url || file),
        url: file.url || file,
        status: 'success'
      }))
    },

    // 从URL获取文件名
    getFileName(url) {
      if (!url) return ''
      const parts = url.split('/')
      return parts[parts.length - 1] || '未知文件'
    },

    // 上传前检查
    beforeUpload(file) {
      // 检查文件类型
      if (this.fileType === 'image') {
        const isImage = file.type.startsWith('image/')
        if (!isImage) {
          this.$message.error('只能上传图片文件!')
          return false
        }
      } else if (this.fileType === 'document') {
        const allowedTypes = [
          'application/pdf',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'application/vnd.ms-powerpoint',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'text/plain'
        ]
        if (!allowedTypes.includes(file.type)) {
          this.$message.error('只能上传PDF、Word、Excel、PPT、TXT文件!')
          return false
        }
      }

      // 检查文件大小
      const isLtSize = file.size / 1024 / 1024 < this.fileSize
      if (!isLtSize) {
        this.$message.error(`文件大小不能超过 ${this.fileSize}MB!`)
        return false
      }

      return true
    },

    // 上传成功
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        file.url = response.data.url
        this.updateValue()
        this.$message.success('上传成功')
      } else {
        this.$message.error(response.msg || '上传失败')
        this.handleRemove(file, fileList)
      }
    },

    // 上传失败
    handleError(error, file, fileList) {
      console.error('上传失败:', error)
      this.$message.error('上传失败，请重试')
      this.handleRemove(file, fileList)
    },

    // 删除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.updateValue()
    },

    // 预览文件
    handlePreview(file) {
      if (this.fileType === 'image') {
        this.previewUrl = file.url
        this.previewVisible = true
      } else {
        // 文档类型直接下载或在新窗口打开
        window.open(file.url, '_blank')
      }
    },

    // 超出文件数量限制
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${this.limit} 个文件`)
    },

    // 更新值
    updateValue() {
      const files = this.fileList
        .filter(file => file.status === 'success' && file.url)
        .map(file => ({
          name: file.name,
          url: file.url
        }))

      let value
      if (this.multiple) {
        value = files
      } else {
        value = files.length > 0 ? files[0].url : ''
      }

      this.$emit('input', value)
      this.$emit('change', value)
    },

    // 清空文件
    clearFiles() {
      this.fileList = []
      this.updateValue()
    },

    // 手动上传
    submit() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style lang="scss" scoped>
.file-upload {
  .upload-component {
    ::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.2s;

      &:hover {
        border-color: #409eff;
      }
    }

    ::v-deep .el-upload-list__item {
      transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
    }

    ::v-deep .el-upload--picture-card {
      width: 148px;
      height: 148px;
      line-height: 146px;
    }

    ::v-deep .el-upload-list--picture-card .el-upload-list__item {
      width: 148px;
      height: 148px;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
      width: 146px;
      height: 146px;
      line-height: 146px;
      text-align: center;
    }
  }

  .el-upload__tip {
    font-size: 12px;
    color: #606266;
    margin-top: 7px;
  }
}
</style>